//
//  BaseTabBarController.swift
//  SwiftDeme
//
//  Created by apple on 2019/7/7.
//  Copyright © 2019 yimiSun. All rights reserved.
//

import UIKit

/**
 *  自定义系统底部导航
 */
class BaseTabBarController: UITabBarController {
    
    //MARK: - proterty
    private let _unselectColor:UIColor = UIColor.init().colorFromHexInt(hex: 0xBFC7D4)
    
    /** 首页 */
    private lazy var _hmvc = MainViewController()
    private lazy var _kvc = TwoViewController()
    private lazy var _gameVC = GameViewController()
    
    private lazy var offsetTitleY = CGFloat.init(-4)
    private lazy var offsetImageY = CGFloat.init(1)
    
    
    //MARK: - override func
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //设置启动视图
        //self.setLaunchView()
        
        //指定委托
        self.delegate = self
        
        if UIDevice.current.isiPhoneX() {
            offsetTitleY = CGFloat.init(6)
            offsetImageY = CGFloat.init(-3)
        }
        
        //设置栏目
        self.setViewControler(viewController:_hmvc, AndTitle: "分时", AndImage: "home.png", WithSelectImage: "home_hover.png")
        self.setViewControler(viewController:_kvc, AndTitle: "K线", AndImage: "order.png", WithSelectImage: "order_hover.png")
        self.setViewControler(viewController:_gameVC, AndTitle: "Game", AndImage: "message.png", WithSelectImage: "message_hover.png")
        
        //清除顶部线
        Utils.shareInstance().clearnTabBarTopLine(tabBar: self.tabBar)
        
        //设置上阴影
        Utils.shareInstance().setViewShadowStyle(uView: self.tabBar,
                           shadowRadius: CGFloat.init(4),
                           shadowOffset: CGSize.init(width: 0, height: -0.8))
        
        //背景
        self.tabBar.backgroundColor = Setting.K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        //self.tabBar.backgroundImage = UIImage.init(named: "tabbar_bg.png")
        
        //选中背景
        //self.tabBar.selectionIndicatorImage = UIImage.init(named: "tabbar_select_bg.png")
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        //设置高度
        Utils.shareInstance().setTabbarHeight(tabBar: self.tabBar)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    deinit {
        print("\(self.className()) 已销毁")
    }

}


//MARK: -
extension BaseTabBarController {
    /** 设置子视图 */
    private func setViewControler(viewController:UIViewController,
                                  AndTitle _title:String,
                                  AndImage _image:String,
                                  WithSelectImage _selectImage:String,
                                  AndTitleOffsetX _offsetX:CGFloat? = nil,
                                  AndImgOffsetY _offsetY:CGFloat? = nil) -> Void {
        
        viewController.title = _title
        viewController.tabBarItem.titlePositionAdjustment = .init(horizontal: 0, vertical: offsetTitleY)
        if _offsetX != nil {
            viewController.tabBarItem.titlePositionAdjustment = .init(horizontal: _offsetX!, vertical: offsetTitleY)
        }

        viewController.tabBarItem.image = UIImage.init(named: _image)?.withRenderingMode(.alwaysOriginal)
        viewController.tabBarItem.selectedImage = UIImage.init(named: _selectImage)?.withRenderingMode(.alwaysOriginal)

        viewController.tabBarItem.imageInsets = UIEdgeInsets(top: -offsetImageY, left: 0, bottom: offsetImageY, right: 0)
        if _offsetY != nil {
            viewController.tabBarItem.imageInsets = UIEdgeInsets(top: _offsetY!, left: 0, bottom: -offsetImageY, right: 0)
        }
        
        //未选中的颜色
        viewController.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : _unselectColor], for: .normal)
        //选中颜色(默认与主题色一致)
        viewController.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : Setting.K_APP_TINT_COLOR], for: .selected)
        
        self.addChild(viewController)
    }
    
    
    /** 设置启动视图 */
    private func setLaunchView(){
        let _isFirst:Bool? = UserDefaults.standard.bool(forKey: Setting.K_APP_START_GUIDE_VIEW_HAS_KEY)
        if _isFirst == nil || _isFirst == false {
            
            DispatchQueue.global().async {
                //...
                
                DispatchQueue.main.async {
                    //...
                }
            }
        }
    }

    /// 点击动画
    private func tabbarAnimationFor(Index ix:Int) {
        let tabBarButtons = NSMutableArray.init(array: self.tabBar.subviews.filter({ return $0.isKind(of: NSClassFromString("UITabBarButton")!) }))
        
        //点击动画
        if tabBarButtons.count > ix {
            let tabBarButton:UIView? = tabBarButtons[ix] as? UIView

            let basicAnimation = CABasicAnimation(keyPath: "transform.scale")
            basicAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            basicAnimation.duration = 0.08
            basicAnimation.repeatCount = 1
            basicAnimation.autoreverses = true
            basicAnimation.fromValue = NSNumber(value: 0.7)
            basicAnimation.toValue = NSNumber(value: 1.3)
            tabBarButton?.layer.add(basicAnimation, forKey: nil)
        }
    }
    
}


//MARK: - UITabBarControllerDelegate
extension BaseTabBarController : UITabBarControllerDelegate {
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        
        let index:Int = tabBar.items?.firstIndex(where: { $0 == item }) ?? 0
        self.tabbarAnimationFor(Index: index)
    }
}


//MARK: - 屏幕旋转
extension BaseTabBarController {
    
    open override var shouldAutorotate: Bool {
        get{
            return selectedViewController?.shouldAutorotate ?? true
        }
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return selectedViewController?.supportedInterfaceOrientations ?? .portrait
        }
    }
}
